package com.teamwork.common.commonconfig;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.util.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyConvert implements Converter<String, Date> {

    private static final String format = "yyyy-MM-dd HH:mm:ss";
    private static final String formate="yyyy/MM/dd HH:mm:ss";
    private static final String shortformat="yyyy-MM-dd";
    private static final String shortformate="yyyy/MM/dd";


    @Override
    public Date convert(String s) {
        if(StringUtils.isEmpty(s)){
            return null;
        }
        s=s.trim();
        if(s.contains("-")){
            SimpleDateFormat dateFormat;
            if(s.contains(":")){
                //yyyy-MM-dd HH:mm:ss格式
                dateFormat=new SimpleDateFormat(format);
            }else {
                //yyyy-MM-dd格式
                dateFormat=new SimpleDateFormat(shortformat);
            }
            try {
                return dateFormat.parse(s);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } else if (s.contains("/")) {
            SimpleDateFormat dateFormat;
            if(s.contains(":")){
                //yyyy/MM/dd HH:mm:ss格式
                dateFormat=new SimpleDateFormat(formate);
            }else {
                //yyyy/MM/dd格式
                dateFormat=new SimpleDateFormat(shortformate);
            }
            try {
                return dateFormat.parse(s);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public JavaType getInputType(TypeFactory typeFactory) {
        return null;
    }

    @Override
    public JavaType getOutputType(TypeFactory typeFactory) {
        return null;
    }
}
